package pers.hl.module_main.book_detail

import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.BaseSectionQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import pers.hl.common.base.ext.showMessage
import pers.hl.common.utils.UiUtils
import pers.hl.lib_global.common.GlideUtils
import pers.hl.lib_global.common.MMKVHelper
import pers.hl.lib_global.model.bean.Book
import pers.hl.lib_global.model.bean.Comment
import pers.hl.lib_global.model.enums.BookStatus
import pers.hl.lib_global.model.enums.FileType
import pers.hl.module_main.R
import pers.hl.module_main.common.CommonDialog
import pers.hl.module_main.common.PageHelper
import pers.hl.module_main.databinding.ItemDetailRvTitleBinding
import pers.hl.module_main.databinding.ItemDetailTextBinding
import pers.hl.module_main.databinding.ItemRvCommentBinding
import pers.hl.module_main.databinding.LayoutHeaderBookDetailBinding

class DetailAdapter(private val activity: BookDetailActivity) :
    BaseSectionQuickAdapter<DetailItem, BaseViewHolder>(R.layout.layout_header_book_detail) {

    init {
        addItemType(DetailItem.TYPE_TITLE, R.layout.item_detail_rv_title)
        addItemType(DetailItem.TYPE_DESC, R.layout.item_detail_text)
        addItemType(DetailItem.TYPE_COMMENT, R.layout.item_rv_comment)
    }

    override fun convert(holder: BaseViewHolder, item: DetailItem) {
        when (holder.itemViewType) {
            DetailItem.TYPE_TITLE -> {
                val title = item.getData() as DetailItem.Title
                showTitle(holder, title)
            }
            DetailItem.TYPE_DESC -> {
                val text = item.getData() as DetailItem.Text
                showDesc(holder, text)
            }
            DetailItem.TYPE_COMMENT -> {
                val comment = item.getData() as Comment
                showComment(holder, comment)
            }
        }

    }

    override fun convertHeader(helper: BaseViewHolder, item: DetailItem) {
        val headerBinding = LayoutHeaderBookDetailBinding.bind(helper.itemView)
        headerBinding.apply {
            val data = item.getData() as Book
            GlideUtils.loadBookImage(ivBook.context, ivBook, data)
            UiUtils.setMarquee(tvTitle)
            tvTitle.text = data.bookName
            tvStatus.text = data.bookStatus?.let { getStatusName(it) }
            tvAuthor.text = String.format("作者：%s", data.bookAuthor)
            tvOwner.text = String.format("持有人：%s", data.ownerName)
            tvOwner.tag = data.bookOwner
            tvTagName.text = String.format("标签：%s", data.tagName)

            when (data.bookStatus) {
                Book.STATUS_BORROWING, Book.STATUS_BORROWED, Book.STATUS_NONE -> {
                    tvBorrow.text = "不可借阅"
                    tvBorrow.setBackgroundColor(getColor(R.color.darkgray))
                    tvBorrow.setTextColor(getColor(R.color.white))
                }
                else -> {
                    tvBorrow.text = "借阅"
                    tvBorrow.setBackgroundColor(getColor(R.color.white))
                    tvBorrow.setTextColor(getColor(R.color.black))
                }
            }
            // 本人书籍展示二维码
            if (isMyBook(data)) {
                tvBorrow.text = "二维码"
            }
            tvBorrow.setOnClickListener {
                if (isMyBook(data)) {
                    // 本人书籍展示二维码
                    data.bookId?.let { it1 -> CommonDialog.createQrCodeDialog(context, FileType.BOOK_QR_CODE.value(), it1).show() }
                    return@setOnClickListener
                }
                if (data.bookStatus == Book.STATUS_BORROWING || data.bookStatus == Book.STATUS_BORROWED) {
                    return@setOnClickListener
                }
                activity.borrowBook(data)
            }
            tvOwner.apply {
                setOnClickListener {
                    val ownerId = tag as Int
                    if (ObjectUtils.isEmpty(ownerId)) {
                        showMessage("数据错误，未找到该用户")
                        return@setOnClickListener
                    }
                    PageHelper.startUserHomePage(context, ownerId)
                }
            }
        }
    }

    private fun isMyBook(data: Book): Boolean {
        return data.bookOwner == MMKVHelper.getUser()?.userId
    }

    private fun getColor(resId: Int): Int {
        return ContextCompat.getColor(context, resId)
    }

    private fun getStatusName(bookStatus: Int): String {
        return BookStatus.getValueStr(bookStatus)
    }

    private fun showTitle(holder: BaseViewHolder, title: DetailItem.Title) {
        val binding = ItemDetailRvTitleBinding.bind(holder.itemView)
        binding.apply {
            tvTitle.text = title.data
            ivComment.visibility = if (title.type == DetailItem.TYPE_COMMENT) View.VISIBLE else View.GONE
            ivComment.setOnClickListener {
                showInputCommentDialog()
            }
        }
    }

    private fun showDesc(holder: BaseViewHolder, text: DetailItem.Text) {
        val binding = ItemDetailTextBinding.bind(holder.itemView)
        binding.apply {
            tvText.text = text.data
            root.setOnClickListener {
                when (text.type) {
                    DetailItem.TYPE_EMPTY -> {
                        LogUtils.d("点击简介空数据")
                    }
                    DetailItem.TYPE_COMMENT -> {
                        showInputCommentDialog()
                    }
                }
            }
        }

    }

    private fun showInputCommentDialog() {
        val dialog = CommonDialog.createCommon(
            context,
            R.layout.layout_input_dialog,
            Gravity.CENTER
        ) { layer ->
            val etContent = layer.getView<EditText>(R.id.etContent)
            val tvConfirm = layer.getView<TextView>(R.id.tvConfirm)
            val tvCancel = layer.getView<TextView>(R.id.tvCancel)
            etContent.hint = "请输入评论"
            tvConfirm.setOnClickListener {
                layer.dismiss()
                val comment = etContent.text.toString()
                if (TextUtils.isEmpty(comment)) {
                    showMessage("请输入评论")
                    return@setOnClickListener
                }
                activity.addComment(comment)
            }
            tvCancel.setOnClickListener {
                layer.dismiss()
            }
        }
        dialog.show()
    }

    private fun showInputReplyDialog(cmtId: Int?) {
        val dialog = CommonDialog.createCommon(
            context,
            R.layout.layout_input_dialog,
            Gravity.CENTER
        ) { layer ->
            val etContent = layer.getView<EditText>(R.id.etContent)
            val tvConfirm = layer.getView<TextView>(R.id.tvConfirm)
            val tvCancel = layer.getView<TextView>(R.id.tvCancel)
            etContent.hint = "请输入回复"
            tvConfirm.setOnClickListener {
                layer.dismiss()
                val replyContent = etContent.text.toString()
                if (TextUtils.isEmpty(replyContent)) {
                    showMessage("请输入回复")
                    return@setOnClickListener
                }
                activity.addReply(cmtId, replyContent)
            }
            tvCancel.setOnClickListener {
                layer.dismiss()
            }
        }
        dialog.show()
    }

    private fun showComment(holder: BaseViewHolder, comment: Comment) {
        val binding = ItemRvCommentBinding.bind(holder.itemView)
        binding.apply {
            comment.cmtUserId?.let {
                GlideUtils.loadUserAvatar(
                    ivAvatar.context, ivAvatar,
                    it, R.drawable.ic_personal_center
                )
                tvCommenter.text = if (StringUtils.isEmpty(comment.userName)) "匿名用户" else comment.userName
            }
            tvTime.text = TimeUtils.date2String(comment.cmtTime)
            tvComment.text = comment.cmtInfo
            tvReplyCount.text = String.format("共%s条回复 >", comment.replyCount.toString())
            tvReplyCount.visibility = if (comment.replyCount > 0) View.VISIBLE else View.GONE
            root.setOnClickListener {
                showCommentOperationDialog(comment)
            }
            tvReplyCount.setOnClickListener {
                activity.fetchReplyList(comment)
            }
            ivAvatar.setOnClickListener {
                PageHelper.startUserHomePage(context, comment.cmtUserId)
            }
        }
    }

    private fun showCommentOperationDialog(comment: Comment) {
        val dialog = CommonDialog.createBottomList(
            context,
            mutableListOf("回复", "删除"),
            convertBlock = { holder, item ->
                holder.getView<TextView>(R.id.tvItem).text = item
            },
            onItemClick = { layer, adapter, position, item ->
                layer.dismiss()
                when (position) {
                    0 -> showInputReplyDialog(comment.cmtId)
                    1 -> activity.deleteComment(comment)
                }
            })
        dialog.show()
    }


}